#!/usr/bin/perl -w
#
# This script generates an ihex binary image and XML description
# from an srec binary image. These are used by the Deluge binary
# image dissemination service.
#
#$Id: tos-write-image.in,v 1.1.2.1 2005/08/08 19:03:11 idgay Exp $
#@author Jonathan Hui <jwhui@cs.berkeley.edu>
#
use strict;

my $MaxNameLength = 10;

if ( @ARGV == 0 ) {
  print "usage: tos-write-image [ident_flags] [exe_file]\n";
  exit 0;
}

my %ident_flags = ();
my $exe = "";
my $ihex = "";
my $objdump = "avr-objdump";

for my $arg (@ARGV) {
  if ($arg =~ /^-DIDENT_(.+)=0x(.+)$/) {
    $ident_flags{lc($1)} = uc($2);
  }
  elsif ($arg =~ /^-DIDENT_(.+)=(.+)$/) {
    $ident_flags{lc($1)} = $2;
  }
  elsif ($arg =~ /^--ihex=(.+)$/) {
    $ihex = $1;
  }
  elsif ($arg =~ /^--exe=(.+)$/) {
    $exe = $1;
  }
  elsif ($arg =~ /^--objdump=(.+)$/) {
    $objdump = $1;
  }
}

my $deluge_support = "no";
# See if app has deluge included
open( EXE, "$objdump -t $exe |") or die "Cannot open exe file: $!\n";
while(<EXE>) {
  if ( /Deluge/ ) {
    $deluge_support = "yes";
  }
}
close(EXE);
$ident_flags{"deluge_support"} = $deluge_support;

open ( IHEX, $ihex ) or die "Cannot open ihex file: $!\n";

print "<tos_image>\n";
print "  <ident>\n";
for my $flag (keys %ident_flags) {
  print "    <$flag>$ident_flags{$flag}</$flag>\n";
}
print "  </ident>\n";
print "  <image format=\"ihex\">\n";

while ( my $line = <IHEX> ) {
  print $line;
}

print "  </image>\n";
print "</tos_image>\n";
